// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"uos_uwsgi_exporter/internal/config"
	"uos_uwsgi_exporter/internal/server"
	"uos_uwsgi_exporter/pkg/logger"
)

var (
	version = "dev"
	commit  = "unknown"
	date    = "unknown"
)

func main() {
	// 解析命令行参数
	cfg := config.ParseFlags()

	// 初始化日志器
	appLogger, err := initLogger(cfg)
	if err != nil {
		fmt.Printf("Failed to initialize logger: %v\n", err)
		os.Exit(1)
	}

	// 显示版本信息
	if cfg.ShowVersion {
		fmt.Printf("uos_uwsgi_exporter version %s (commit: %s, date: %s)\n", version, commit, date)
		os.Exit(0)
	}

	// 记录启动信息
	appLogger.WithFields(map[string]interface{}{
		"version": version,
		"commit":  commit,
		"date":    date,
		"config":  cfg.GetConfigSummary(),
	}).Info("Starting uWSGI Exporter")

	// 创建HTTP服务器
	srv := server.New(cfg)

	// 启动服务器
	go func() {
		appLogger.WithFields(map[string]interface{}{
			"address": cfg.Address,
			"port":    cfg.Port,
		}).Info("Starting HTTP server")

		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			appLogger.WithError(err).Fatal("Server error occurred")
		}
	}()

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	appLogger.Info("Received shutdown signal, starting graceful shutdown")

	// 优雅关闭
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		appLogger.WithError(err).Fatal("Server forced to shutdown")
	}

	appLogger.Info("Server shutdown completed successfully")
}

// initLogger 初始化日志器
func initLogger(cfg *config.Config) (logger.Logger, error) {
	var appLogger logger.Logger
	var err error

	// 根据配置创建不同类型的日志器
	if cfg.LogFile != "" {
		// 输出到文件和控制台
		appLogger, err = logger.NewWithFileAndConsole(cfg.LogFile, cfg.LogLevel)
		if err != nil {
			return nil, fmt.Errorf("failed to create file logger: %w", err)
		}
	} else {
		// 只输出到控制台
		var output io.Writer = os.Stdout
		appLogger, err = logger.NewWithConfig(cfg.LogLevel, output, "text")
		if err != nil {
			return nil, fmt.Errorf("failed to create console logger: %w", err)
		}
	}

	// 设置全局默认日志器
	logger.DefaultLogger = appLogger

	return appLogger, nil
}
